package cn.domypay.mail.control;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import javax.mail.*;

import cn.domypay.mail.base.SmtpBiz;
import cn.domypay.mail.base.SwanetAuthenticate;
import cn.domypay.mail.bean.EmailMessage;
import cn.domypay.mail.bean.Mailbox;
import cn.domypay.mail.conf.DomypayMail;
import cn.domypay.mail.thread.MainSenderThread;


/**
 * send email
 * <p>
 * Title:
 * </p>
 * <p>
 * Description: Swanet common tools
 * </p>
 * <p>
 * Copyright: Copyright (c) 2005
 * </p>
 * <p>
 * Company: Swanet
 * </p>
 * 
 * @author sun lifan
 * @version 1.0
 */
public class EmailSender {

	private Mailbox mailbox;
	
	public EmailSender(Mailbox mailbox) {
		this.mailbox = mailbox;
	}

	/**
	 * send
	 * 
	 * @param msg
	 *            EmailMessage
	 * @throws Exception
	 */
	public void send(EmailMessage msg) throws Exception {
		// System.out.println("msg's content:"+msg.getContent());
		Properties mailProps = new Properties();
		
		SmtpBiz smtpBiz=new SmtpBiz();
		
		if (mailbox != null) {
			if(DomypayMail.NEED_SSL.equals(mailbox.getSmtpSsl()))
			{
				/**
				 * 如果需要进行ssl连接方式，获取ssl连接方式的smtp协议设置
				 */
				mailProps = smtpBiz.getSmtp_SslProp(mailbox);
				
			}else{
				/**
				 * 如果不需要进行ssl连接方式，获取普通smtp协议设置
				 */
				mailProps=smtpBiz.getSmtpProp(mailbox);
			}		
		}

		// Create Authenticator object for session
		SwanetAuthenticate pAuth = new SwanetAuthenticate(mailbox.getUsername(), mailbox.getPassword());
		Session session = Session.getInstance(mailProps, pAuth);

		Message mail = EmailHelper.compose(session, msg);
		smtpBiz.smtpSender(session, mail, mailbox);
	}
	
	/**
	 * param��list is a object of EmailMessage in the list;
	 * param: cmailbox is user's mailbox;
	 * param: resultList is the result list,if it's empty sender success,else sender failure;
	 * @throws Exception 
	 */
	public List sendMessageListForThread(List<EmailMessage> list) throws Exception {
		// TODO �Զ���ɷ������
		
		SmtpBiz smtpBiz = new SmtpBiz();
		
		Iterator subsIter = list.iterator();
		
		Properties mailProps = new Properties();
		
		if(DomypayMail.NEED_SSL.equals(mailbox.getSmtpSsl()))
		{
			/**
			 * 如果需要进行ssl连接方式，获取ssl连接方式的smtp协议设置
			 */
			mailProps = smtpBiz.getSmtp_SslProp(mailbox);
			
		}else{
			/**
			 * 如果不需要进行ssl连接方式，获取普通smtp协议设置
			 */
			mailProps = smtpBiz.getSmtpProp(mailbox);
			
		}	
		
		SwanetAuthenticate pAuth = new SwanetAuthenticate(mailbox
				.getUsername(), mailbox.getPassword());
		
		Session session = Session.getInstance(mailProps, pAuth);
		
		Transport transport;
		/**
		 * 判断用户邮件服务器是否可以成功连接;
		 * 如果可以成功连接，则继续进行发送;
		 * 如果不能成功连接，则跳出连接;
		 */
		transport = smtpBiz.openSmtpConnection(session, mailbox);
		
		/**
		 * 以下进行多线程批量发送邮件
		 */
		MainSenderThread thread;
		
		/**
		 * 生成邮件发送线程组
		 */
		ThreadGroup sendAllThread = new ThreadGroup("mailSender");
		
		int i=0;
		
		List resultList = new ArrayList();
		
		while(subsIter.hasNext())
		{
			
			EmailMessage emailMessage = (EmailMessage)subsIter.next();
			
			Message message;
			/**
			 * 解析邮件信息，转换成邮件标准message格式
			 */
			message = EmailHelper.compose(session, emailMessage);
				
			thread = new MainSenderThread(sendAllThread,"mailSender"+i,transport,message ,resultList);
				
			thread.start();
				
			i++;
		}
		
		
		senderWait(sendAllThread);
		
		/**
		 * 如果邮件发送线程组中还有意料之外的线程活跃，则强制关闭线程组
		 */
		if(sendAllThread.activeCount()>0)
		{
			sendAllThread.destroy();
		}
		/**
		 * 邮件发送结束，关闭连接
		 */
		smtpBiz.closeSmtpConnection(transport);
		return resultList;
	}
	/**
	 * 邮件发送等待监视器
	 * @param group
	 * @return
	 * @throws InterruptedException 
	 */
	public boolean senderWait(ThreadGroup group) throws InterruptedException
	{	
		/*
		 * 当线程组中不存在活跃线程的时候，退出发送等待
		 */
		if(0 != group.activeCount())
		{
			/**
			 * 当线程组中有活跃线程存在，根据活跃线程数，
			 * 计算出需要等待的时间， 并进行发送等待
			 */
			Thread.sleep(group.activeCount()*100);
			senderWait(group);
			return true;
		}
		return false;
	}

	public void sendMessageListForTimeTask(List<EmailMessage> list, int waitTime) throws Exception {
		// TODO �Զ���ɷ������
		
		if(0 == waitTime)
		{
			sendMessageListForThread(list);
		}else{
			Thread.sleep(waitTime);
			sendMessageListForThread(list);
		}
	}
//	public static void main(String[] agrs) throws Exception {
//		try {
//			List sendList = new ArrayList();
//			CMailbox mailbox = new CMailbox();
//			mailbox.setPassword("5211314");
//			mailbox.setUserName("eghostsun2@gmail.com");
//			mailbox.setDomain("gmail.com");
//			mailbox.setSmtpPort("465");
//			mailbox.setSmtpSsl("1");
//			mailbox.setSmtpHost("pop.gmail.com");
//			mailbox.setIsAuth("1");
//			mailbox.setIsPass("1");
//			mailbox.setMailbox("eghostsun@gmail.com");
//			
//			EmailSender sender = new EmailSender(mailbox);
//			
//			EmailMessage msg = new EmailMessage();
//			for(int i=0;i<50;i++)
//			{
//				com.pominfo.framework.mail.bean.EmailUser[] tos = new com.pominfo.framework.mail.bean.EmailUser[1];
//				com.pominfo.framework.mail.bean.EmailUser to = new com.pominfo.framework.mail.bean.EmailUser("sunlifan05@126.com"); // judyz@hz.webex.com
//				tos[0] = to;
//				com.pominfo.framework.mail.bean.EmailUser from = new com.pominfo.framework.mail.bean.EmailUser("eghostsun@gmail.com");
//				msg.setSubject("test");
//	
//				msg.setContentType("text/html");
//	
//				String content = "<P>79798897</P>" + "<P>s</P>";
//				msg.setContent(content);
//				msg.setTo(tos);
//				msg.setFrom(from);
//				sendList.add(msg);
//			}
//			List resultList = new ArrayList();
//			sender.sendMessageListForThread(sendList, resultList);
//			if(null == resultList || resultList.isEmpty())
//			{
//				System.out.println("���ͳɹ�");
//			}else{
//				System.out.println(resultList.size());
//			}
//			
//		} catch (Exception e) {
//			e.printStackTrace();
//
//		}
//
//	}


}
